import pygame, sys, math, random, time

pygame.init()

from Block import Block
from Player import Player
from HardBlock import HardBlock
from Enemy import Enemy
from Background import Background
from WaterBlock import WaterBlock
from BallBlock import BallBlock
from ChangeBlock import ChangeBlock
from LavaBlock import LavaBlock
from TurtleBlock import TurtleBlock
from ChestyBlock import ChestyBlock
from ExitBlock import ExitBlock
from FruitOfDoom import FruitOfDoom

clock = pygame.time.Clock()

width = 800
height = 600
size = width, height

blocksize = [50,50]
playersize = [40,40]

screen = pygame.display.set_mode(size)
bgColor = r,g,b = 0,0,0

blocks = pygame.sprite.Group()
hardBlocks = pygame.sprite.Group()
enemies = pygame.sprite.Group()
tackenemies = pygame.sprite.Group()
fruitofdoom = pygame.sprite.Group()
backgrounds = pygame.sprite.Group()
players = pygame.sprite.Group()
turtleblocks = pygame.sprite.Group()
lavablocks = pygame.sprite.Group()
waterblocks = pygame.sprite.Group()
changeblocks = pygame.sprite.Group()
ballblocks = pygame.sprite.Group()
chestyblocks = pygame.sprite.Group()
exitblocks = pygame.sprite.Group()
all = pygame.sprite.OrderedUpdates()

Player.containers = (all, players)
Block.containers = (all, blocks)
HardBlock.containers = (all, hardBlocks, blocks)
Enemy.containers = (all, enemies, tackenemies)
FruitOfDoom.containers = (all, enemies, fruitofdoom)
Background.containers = (all, blocks)
WaterBlock.containers = (all, blocks, waterblocks)
BallBlock.containers = (all, changeblocks, hardBlocks, ballblocks, blocks)
LavaBlock.containers = (all, changeblocks, lavablocks, blocks)
TurtleBlock.containers = (all, changeblocks, hardBlocks, turtleblocks, blocks)
ChestyBlock.containers = (all, changeblocks, chestyblocks, blocks)
ExitBlock.containers = (all, changeblocks, hardBlocks, exitblocks, blocks)

bg = Background("rsc/bg/mainbg.png", size)
chestnumber = 0

def loadLevel(level):
    f = open(level+".lvl", 'r')
    lines = f.readlines()
    f.close()
    
    newlines = []
    
    for line in lines:
        newline = ""
        for c in line:
            if c != "\n":
                newline += c
        newlines += [newline]
        
    #for line in newlines:
        #print line
    
    for y, line in enumerate(newlines):
        for x, c in enumerate(line):
            if c == "#":
                HardBlock("rsc/blocks/black.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "p":
                Block("rsc/blocks/purple.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "r":
                Block("rsc/blocks/rainbow.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "~":
                WaterBlock("rsc/blocks/blue.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == '"'  :
                Block("rsc/blocks/grass.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)  
            elif c == "x":
                #Sprint "Loading!", [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2]
                BallBlock("rsc/blocks/brown.png",
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "l":
                LavaBlock("rsc/blocks/Lava.png", [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "t":
                TurtleBlock("rsc/blocks/torkoalblock.png",
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)                                            
            elif c == "m":
                ExitBlock("rsc/blocks/door.png",
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "k":
                Block("rsc/blocks/krag.png",
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)          
            elif c == "d":
                Block("rsc/blocks/drag.png",
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)     
                      
    f = open(level+".tng", 'r')
    lines = f.readlines()
    f.close()
    
    newlines = []
    
    for line in lines:
        newline = ""
        for c in line:
            if c != "\n":
                newline += c
        newlines += [newline]
        
    #for line in newlines:
        #print line
    
    for y, line in enumerate(newlines):
        for x, c in enumerate(line):
            if c == "@":
                player = Player([(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
                     playersize,
                     size)
            elif c == "e":
                Enemy("rsc/enemy/tackattacks.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      playersize)
            elif c == "f":
                FruitOfDoom("rsc/enemy/deathlime.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      playersize)
            elif c == "c":
                ChestyBlock("rsc/blocks/key.png",
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
                      
    for each in all.sprites():
        each.fixLocation(player.offsetx, player.offsety)
     
levels = ["rsc/levels/Firetemple",
          "rsc/levels/watertemple",
          "rsc/levels/level3",
          "rsc/levels/proofthatjoeisdumb"]
          
level = 0
loadLevel(levels[level])
player1 = players.sprites()[0]

while True:
    while player1.living:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()   
                
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
                    player1.direction("right")
                if event.key == pygame.K_a or event.key == pygame.K_LEFT:
                    player1.direction("left")
                if event.key == pygame.K_w or event.key == pygame.K_UP:
                    player1.direction("up")
                if event.key == pygame.K_s or event.key == pygame.K_DOWN:
                    player1.direction("down")
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
                    player1.direction("stop right")
                if event.key == pygame.K_a or event.key == pygame.K_LEFT:
                    player1.direction("stop left")
                if event.key == pygame.K_w or event.key == pygame.K_UP:
                    player1.direction("stop up")
                if event.key == pygame.K_s or event.key == pygame.K_DOWN:
                    player1.direction("stop down")
                    
        playersHitBlocks = pygame.sprite.groupcollide(players, hardBlocks, False, False)
        for player in playersHitBlocks:
            for block in playersHitBlocks[player]:
                player.collideBlock(block)
        
        enemiesHitBlocks = pygame.sprite.groupcollide(enemies, hardBlocks, False, False)           
        for enemy in enemiesHitBlocks:
            for block in enemiesHitBlocks[enemy]:
                enemy.collideBlock(block)
                
        enemiesHitEnemies = pygame.sprite.groupcollide(enemies, enemies, False, False)
        for enemy in enemiesHitEnemies:
            for otherEnemy in enemiesHitEnemies[enemy]:
                enemy.collideBlock(otherEnemy)
                
                    
        playersHitBallBlocks = pygame.sprite.groupcollide(players, ballblocks, False, False)
        for player in playersHitBallBlocks:
            for block in playersHitBallBlocks[player]:
                player.collideBallBlock(block)
                print "collideballblock"
               
        playersHitTurtleBlocks = pygame.sprite.groupcollide(players, turtleblocks, False, False)
        for player in playersHitTurtleBlocks:
            for block in playersHitTurtleBlocks[player]:
                player.collideTurtleBlock(block)
                print "collideturtleblock"   

        playersHitChestBlocks = pygame.sprite.groupcollide(players, chestyblocks, False, True)
        for player in playersHitChestBlocks:
            for block in playersHitChestBlocks[player]:
                chestnumber += 1    
                block.kill
                
        playersHitExitBlocks = pygame.sprite.groupcollide(players, exitblocks, False, False)
        for player in playersHitExitBlocks:
            for block in playersHitExitBlocks[player]:
                if player1.imageMode == "normal":
                    if chestnumber == 7:
                        if level < len(levels)-1:
                            level += 1
                        else:
                            level = 0
                        for each in all.sprites():
                            each.kill()
                        bg = Background("rsc/bg/mainbg.png", size)
                        screen.blit(bg.image, bg.rect)
                        loadLevel(levels[level])
                        player1 = players.sprites()[0]
                
        playersHitWaterBlocks = pygame.sprite.groupcollide(players, waterblocks, False, False)
        for player in playersHitWaterBlocks:
            for block in playersHitWaterBlocks[player]:
                if player1.imageMode == "normal":
                    player1.living = False
                    deathtype = "drowned"
                    
        playersHitWaterBlocks = pygame.sprite.groupcollide(players, waterblocks, False, False)
        for player in playersHitWaterBlocks:
            for block in playersHitWaterBlocks[player]:
                if player1.imageMode == "lava":
                    player1.living = False
                    deathtype = "lavadrowned"
                    
        playersHitEnemies = pygame.sprite.groupcollide(players, tackenemies, False, False)
        for player in playersHitEnemies:
            for block in playersHitEnemies[player]:
                if player1.imageMode == "ball":
                    player1.living = False                    
                    deathtype = "stabbed"
                    
        playersHitFruitEnemies = pygame.sprite.groupcollide(players, fruitofdoom, False, False)
        for player in playersHitFruitEnemies:
            for block in playersHitFruitEnemies[player]:
                if not player1.imageMode == "ball":
                    player1.living = False                    
                    deathtype = "fruit"    
                    
        playersHitLava = pygame.sprite.groupcollide(players, lavablocks, False, False)
        for player in playersHitLava:
            for block in playersHitLava[player]:
                if not player1.imageMode == "lava":
                    player1.living = False                    
                    deathtype = "lava"
        
        all.update(size,
                   player1.speedx, 
                   player1.speedy, 
                   player1.scrollingx, 
                   player1.scrollingy,
                   player1.realx,
                   player1.realy)

        print chestnumber
        dirty = all.draw(screen)
        pygame.display.update(dirty)
        pygame.display.flip()
        clock.tick(30)
        
    for each in all.sprites():
        each.kill()

     
    while not player1.living:
        chestnumber = 0
        if deathtype == "drowned":
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        player1.living = True 
                        for each in all.sprites():
                            each.kill()
                        bg = Background("rsc/bg/mainbg.png", size)
                        level = 0
                        loadLevel(levels[level])
                        player1 = players.sprites()[0]
            deathscreen = pygame.image.load("rsc/bg/drownscreen.png")
            deathscreen = pygame.transform.scale(deathscreen,size)
            deathrect = deathscreen.get_rect() 
            screen.blit(deathscreen, deathrect)
            dirty = all.draw(screen)
            pygame.display.update(dirty)
            pygame.display.flip()
            clock.tick(30)
        elif deathtype == "lavadrowned":
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        player1.living = True  
                        for each in all.sprites():
                            each.kill()
                        bg = Background("rsc/bg/mainbg.png", size)    
                        level = 0
                        loadLevel(levels[level])
                        player1 = players.sprites()[0]                        
            deathscreen = pygame.image.load("rsc/bg/lavadrownscreen.png")
            deathscreen = pygame.transform.scale(deathscreen,size)
            deathrect = deathscreen.get_rect() 
            screen.blit(deathscreen, deathrect)
            dirty = all.draw(screen)
            pygame.display.update(dirty)
            pygame.display.flip()
            clock.tick(30)    
        elif deathtype == "stabbed":
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        player1.living = True 
                        for each in all.sprites():
                            each.kill()                        
                        bg = Background("rsc/bg/mainbg.png", size)    
                        level = 0
                        loadLevel(levels[level])
                        player1 = players.sprites()[0]                        
            deathscreen = pygame.image.load("rsc/bg/deathbytackattack.png")
            deathscreen = pygame.transform.scale(deathscreen,size)
            deathrect = deathscreen.get_rect() 
            screen.blit(deathscreen, deathrect)
            dirty = all.draw(screen)
            pygame.display.update(dirty)
            pygame.display.flip()
            clock.tick(30) 
        elif deathtype == "lava":
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        player1.living = True
                        for each in all.sprites():
                            each.kill()
                        bg = Background("rsc/bg/mainbg.png", size)    
                        level = 0
                        loadLevel(levels[level])
                        player1 = players.sprites()[0]
            deathscreen = pygame.image.load("rsc/bg/lavadeath.png")
            deathscreen = pygame.transform.scale(deathscreen,size)
            deathrect = deathscreen.get_rect() 
            screen.blit(deathscreen, deathrect)
            dirty = all.draw(screen)
            pygame.display.update(dirty)
            pygame.display.flip()
            clock.tick(30) 
        elif deathtype == "fruit":
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        player1.living = True     
                        for each in all.sprites():
                            each.kill()
                        bg = Background("rsc/bg/mainbg.png", size)
                        level = 0
                        loadLevel(levels[level])
                        player1 = players.sprites()[0]                        
            deathscreen = pygame.image.load("rsc/bg/deathbylime.png")
            deathscreen = pygame.transform.scale(deathscreen,size)
            deathrect = deathscreen.get_rect() 
            screen.blit(deathscreen, deathrect)
            dirty = all.draw(screen)
            pygame.display.update(dirty)
            pygame.display.flip()
            clock.tick(30)    